package homework;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//作业标题(2730)
//二叉树的后序非递归遍历
//
//作业内容
//二叉树的后序非递归遍历
//https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
public class h2730 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty())
        {
            while(cur != null)
            {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if(cur.right == null || cur.right == prev)
            {
                list.add(cur.val);
                prev = cur;
                cur = null;
            }
            else {
                stack.push(cur);
                cur = cur.right;
            }
        }
        return list;
    }
}
